package com.senke.aiagent.controller;

import com.senke.aiagent.agent.SenManus;
import com.senke.aiagent.app.LoveApp;
import com.senke.aiagent.model.dto.LoveChatRequest;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/love")
public class LoveController {

    @Resource
    private LoveApp loveApp;

    @Resource
    private ToolCallback[] allTools;

    @Resource
    private ChatModel dashscopeChatModel;

    // 进行对话
    @PostMapping("/chat/sync")
    public String doChatSync(@RequestBody LoveChatRequest loveChatRequest) {
        isValidChatRequest(loveChatRequest);
        return loveApp.doChat(loveChatRequest.getMessage(), loveChatRequest.getChatId());
    }

    /**
     * 进行对话（流式处理）
     *
     * @param loveChatRequest
     * @return
     */
    @PostMapping(value = "/chat/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> doChatSSE(@RequestBody LoveChatRequest loveChatRequest) {
        // 设置响应内容类型为事件流
        //response.setContentType("text/event-stream");
        // 设置响应字符编码为UTF-8
        //response.setCharacterEncoding("UTF-8");
        isValidChatRequest(loveChatRequest);
        return loveApp.doChatByStream(loveChatRequest.getMessage(), loveChatRequest.getChatId());
    }

    /**
     * 流式调用 Manus 超级智能体
     *
     * @param loveChatRequest
     * @return
     */
    @PostMapping("/manus/chat")
    public SseEmitter doChatWithManus(@RequestBody LoveChatRequest loveChatRequest) {
        isValidChatRequest(loveChatRequest);
        SenManus senManus = new SenManus(allTools, dashscopeChatModel);
        return senManus.runStream(loveChatRequest.getMessage());
    }

    /**
     * 校验聊天请求参数
     *
     * @param loveChatRequest
     */
    private void isValidChatRequest(LoveChatRequest loveChatRequest) {
        String message = loveChatRequest.getMessage();
        if (message == null || message.trim().isEmpty()) {
            throw new RuntimeException("消息不能为空");
        }
        String chatId = loveChatRequest.getChatId();
        if (chatId == null || chatId.trim().isEmpty()) {
            throw new RuntimeException("聊天ID不能为空");
        }
    }
}